package com.laijiale.component;

import cn.hutool.json.JSONUtil;
import com.laijiale.result.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author laijiale
 * @date 2024年12月22日 10:25
 */
@RestControllerAdvice(basePackages = "com.laijiale.controller")
public class ResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //放行到beforeBodyWrite方法
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
                                  Class aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        //若Jackson使用字符串转换器，使用JSOn封装以下在返回字符串，避免爆发转换异常
        if (aClass== StringHttpMessageConverter.class){
            return JSONUtil.toJsonStr(o);
        }
        //若返回值已经是Result类型则直接返回
        if (o instanceof Result){
            return o;
        }
        //统一将Controller的返回值封装为Result类型
        return new Result<>(o);
    }
}